#!/usr/bin/env python
#-*- coding:utf8 -*-
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip _sentinel instance
* limit
* channels
* url
* showas
"""
import re
from util.functions import gooquote
from util.xplor import Xplorer
field = "sites"

def youtube(bot, evt, cmd):
	url = youtube.url % gooquote(cmd.arguments)
	info, html = Xplorer.get_url(url, {"accept-encoding": "identity"})
	video = re.search('<a href="(?P<link>/watch\?v=[^"]+)" class="[^"]+?" dir="[^"]+?" title="[^"]+?" >(?P<title>[^<]+?)</a>', html)
	result = "%s http://www.youtube.com%s" % (video.group("title"), video.group("link").split("&")[0]) if video else url
	if video and cmd.opts["u"]:
		result += " %s" % url
	bot.reply(evt, "&B;You&r;&R;&w;Tube&N; %s", result)
youtube.rule = "youtube"
youtube.url = "http://www.youtube.com/results?search_query=%s"

def google_search(url):
	h = {
		"accept-encoding": "identity",
		"user-agent": "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20120405 Firefox/14.0a1"
	}
	info, html = Xplorer.get_request(url, h)
	r = re.search("<div id=resultStats>(.?)</div>", html)
	if r: bot.reply(evt, r.group(1))
	return re.findall('<h3 class="r"><a href="(http://[^"]+)" ', html)

def google(bot, evt, cmd):
	""".google <search string> [-u] [-all|-l 1/10]- It returns the first result of Google search. &+g;-u&N; append the url, &+g;-l&N; """\
	"""&l;1&N; to &l;10&N; returns another result for the 10 first results. &+g;-all&N; returns all 10 first links provided by Google."""
	search = cmd.arguments.lower()
	url = google.url % (evt.lang, gooquote(search))
	#remember last 5 search
	if len(google.stack)>5:
		google.stack.pop(google.stack.keys()[0])
	if google.stack.has_key(search):
		result = google.stack[search]
	else:
		result = google_search(url)
		google.stack.update({search: result})

	if cmd.opts["all"]:
		result = "%s" % " ".join( ["%s &B;%s&N;" % (result[idx], result[idx+1]) for idx in range(0,len(result)-1,2)]) if result else url
	elif cmd.opts['l'] and cmd.opts['l'].isdigit():
		i = int(cmd.opts['l'])-1
		if 0 > i or i > 9: i = 0
		result = "%s" % result[i] if result else url
	else:
		result = "%s" % result[0] if result else url
	if cmd.opts["u"]:
		result += " %s" % url
	bot.reply(evt, "&B;&l;G&r;o&o;o&l;g&+e;l&r;e&N; %s", result)
google.rule = "google"
google.url = "http://www.google.com/search?hl=%s&q=%s"
google.stack = {}
